package raft

import (
    "os"
    "fmt"
)

// persistLogEntry 将日志条目持久化到文件
func (rf *Raft) persistLogEntry(entry LogEntry) error {
    file, err := os.OpenFile(fmt.Sprintf("log_%d.txt", rf.me), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        return err
    }
    defer file.Close()

    _, err = fmt.Fprintf(file, "%d %s\n", entry.Term, entry.Command)
    if err != nil {
        return err
    }
    return nil
}

// recoverLog 从持久化文件中恢复日志条目
func (rf *Raft) recoverLog() error {
    file, err := os.Open(fmt.Sprintf("log_%d.txt", rf.me))
    if err != nil {
        return err
    }
    defer file.Close()

    var term int
    var command string
    for {
        _, err := fmt.Fscanf(file, "%d %s\n", &term, &command)
        if err != nil {
            break
        }
        rf.log = append(rf.log, LogEntry{Term: term, Command: command})
    }
    return nil
}
